<template>
    <div class="p-grid crud-demo">
        <div class="p-col-12">

            <!--面包屑-->
            <div  style="padding-bottom: 0.95rem;">
                <Breadcrumb :home="home" :model="crumbs"/>
            </div>

            <!--标签栏-->
            <div class="card">
                <h4>销售渠道</h4>
                <p>在这里可以对用户下单渠道进行标记，便于分析各个渠道的收益情况。</p>

                <!--标签栏--选项卡-->
                <TabMenu :model="tabmenuItems" />
                <router-view />

                <!--标签栏--按钮组-->
                <Toast/>
                <Toolbar class="p-mb-12">
                    <template slot="left">
                        <Button type="button" icon="pi pi-refresh" class="p-mr-2 p-button-help" @click="refreshTab" />
                        <Button label="新建" icon="pi pi-plus" class="p-button-success p-mr-2" @click="openNew"/>
                        <Button label="删除" icon="pi pi-trash" class="p-button-danger" @click="confirmDeleteSelected" :disabled="!selectedlists || !selectedlists.length"/>
                    </template>

                    <template slot="right">
                         <span class="p-input-icon-left">
                                <i class="pi pi-search"/>
                                <InputText v-model="search" id="search_input" placeholder="检索..."/>
                            </span>&nbsp;

                    </template>
                </Toolbar>
                <!--标签栏--表格-->
                <DataTable ref="dt" :value="lists" :loading="loading"
                           :selection.sync="selectedlists"
                           :dataKey="dataKey" :rowHover="true"
                           paginatorTemplate=""
                           :scrollable="scrollable" :lazy="true"
                           sortMode="multiple" removableSort  @sort="updateSort($event)"
                           class="p-datatable-customers p-datatable-sm p-datatable-gridlines p-datatable-responsive-demo">

                    <template #loading>
                        <ProgressBar mode="indeterminate"/>
                        <div style="text-align: center">正在努力加载数据，请稍候...</div>
                    </template>
                    <template #empty>
                        <div style="text-align: center">{{empty}}</div>
                    </template>
                    <Column selectionMode="multiple" headerStyle="width: 3rem"  headerClass="p-text-center" bodyClass="p-text-center"></Column>
                    <Column field="id" header="渠道ID" headerStyle="width: 4rem"  headerClass="p-text-center" bodyClass="p-text-center">
                        <template #body="slotProps">
                            <span class="" style="word-wrap:break-word;word-break:break-all;">{{slotProps.data.id}}</span>
                        </template>
                    </Column>

                    <Column field="name" header="渠道名称" headerStyle="width: 12rem"  headerClass="p-text-center" bodyClass="p-text-center">
                        <template #body="slotProps">
                            <span class="list-badge status-success" style="word-wrap:break-word;word-break:break-all;">{{slotProps.data.name}}</span>
                        </template>
                    </Column>
                    <Column field="remarks" header="渠道备注" headerStyle="width: 15rem"  headerClass="p-text-center" bodyClass="p-text-center">
                        <template #body="slotProps">
                            <p><span style="word-wrap:break-word;word-break:break-all;font-weight:bold;">{{slotProps.data.remarks}}</span></p>
                        </template>
                    </Column>
                    <Column field="status" header="生产状态" sortable headerStyle="width: 8rem" headerClass="p-text-center" bodyClass="p-text-center">
                        <template #body="slotProps">
                            <InputSwitch v-model="slotProps.data.status" @click="confirmSwitch(slotProps.data)"/>
                        </template>
                    </Column>
                    <Column field="sort" header="排序" sortable headerStyle="width: 4rem" headerClass="p-text-center" bodyClass="p-text-center">
                        <template #body="slotProps">
                            <span style="word-wrap:break-word;word-break:break-all;">{{slotProps.data.sort}}</span>
                        </template>
                    </Column>

                    <Column field="created_at" header="创建时间" headerStyle="width: 8rem"  sortable headerClass="p-text-center" bodyClass="p-text-center">
                        <template #body="slotProps">
                            {{formatCurrency(slotProps.data.created_at)}}
                        </template>
                    </Column>
                    <Column field="updated_at" header="更新时间" headerStyle="width: 8rem" sortable headerClass="p-text-center" bodyClass="p-text-center"></Column>
                    <Column headerStyle="width: 20em" headerClass="p-text-center" bodyClass="p-text-center">
                        <template #header>
                            <Button type="button" icon="pi pi-cog" label="操作"></Button>
                        </template>
                        <template #body="slotProps" >
                            <span class="p-buttonset">
                            <Button icon="pi pi-pencil" label="编辑"  class="p-button-warning"
                                    @click="editlist(slotProps.data)"/>
                            <Button icon="pi pi-trash" label="删除" class="p-button-danger"
                                    @click="confirmDeletelist(slotProps.data)"/>
                            </span>
                        </template>
                    </Column>
                </DataTable>

                <!--分页-->
                <Paginator slot="left" :first="offset" :rows="limit" :rowsPerPageOptions="[10,20,50,100]"
                           :totalRecords="totalItemsCount" @page="onPage($event)">
                    <template #right="slotProps">
                        显示第 {{slotProps.state.first+1}} 到第 {{(slotProps.state.first+slotProps.state.rows) &lt; totalItemsCount ? (slotProps.state.first+slotProps.state.rows) : totalItemsCount}} 条记录，总共 {{totalItemsCount}} 条记录
                        <Button type="button" icon="pi pi-refresh" @click="refreshTab" />
                    </template>
                </Paginator>

                <!--新建/编辑-->
                <Dialog :visible.sync="listDialog" :style="{width: '450px'}" :header="edit_title" :modal="true"
                        class="p-fluid">
                    <div class="p-field">
                        <label for="province">渠道名称</label>
                        <InputText id="name" v-model.trim="list.name" required="true" autofocus
                                   :class="{'p-invalid': submitted && !list.name}"/>
                        <small class="p-invalid" v-if="submitted && !list.name">渠道名称是必须的。</small>
                    </div>

                    <div class="p-field">
                        <label for="remarks">备注信息</label>
                        <InputText id="remarks" v-model.trim="list.remarks" placeholder="可不填"  autofocus />
                    </div>

                    <div class="p-field">
                        <label for="sort">排序</label>
                        <InputText id="sort" v-model.trim="list.sort" autofocus />
                    </div>

                    <div class="p-field">
                        <h5 style="margin-top: 0">状态开关</h5>
                        <InputSwitch id="status" v-model="list.status" />
                    </div>
                    <template #footer>
                        <Button label="取消" icon="pi pi-times" class="p-button-text" @click="hideDialog"/>
                        <Button label="保存" v-bind:disabled="editSaveDisabled" :icon="editSaveIcon" class="p-button-text"
                                @click="savelist"/>
                    </template>
                </Dialog>

                <!--行删除-->
                <Dialog :visible.sync="deletelistDialog" :style="{width: '450px'}" header="确认" :modal="true">
                    <div class="confirmation-content">
                        <i class="pi pi-exclamation-triangle p-mr-3" style="font-size: 2rem"/>
                        <span v-if="list">确认删除 <b>#{{list.id}}</b>?</span>
                    </div>
                    <template #footer>
                        <Button label="否" icon="pi pi-times" class="p-button-text"
                                @click="deletelistDialog = false"/>
                        <Button label="是" icon="pi pi-check" class="p-button-text" @click="deletelist(list)"/>
                    </template>
                </Dialog>

                <!--批量删除-->
                <Dialog :visible.sync="deletelistsDialog" :style="{width: '450px'}" header="确认" :modal="true">
                    <div class="confirmation-content">
                        <i class="pi pi-exclamation-triangle p-mr-3" style="font-size: 2rem"/>
                        <span v-if="list">确认删除所选项吗?</span>
                    </div>
                    <template #footer>
                        <Button label="否" icon="pi pi-times" class="p-button-text"
                                @click="deletelistsDialog = false"/>
                        <Button label="是" icon="pi pi-check" class="p-button-text" @click="deleteSelectedlists"/>
                    </template>
                </Dialog>

            </div>
        </div>
    </div>
</template>

<script>
    import TableService from '@/api/TableService';
    export default {
        data() {
            return {
                editSaveDisabled: false,
                editSaveIcon: 'pi pi-check p-button-icon p-button-icon-left',
                edit_title: '新建',
                screenWidth: document.body.clientWidth, // 屏幕宽度
                scrollable:false,  //列表是否可滚动，屏幕宽度低于960时启用移动端预览模式，切换为：fasle
                lists: null,
                empty: '没有找到匹配的记录',
                listDialog: false,
                deletelistDialog: false,
                deletelistsDialog: false,
                submitted: false,
                list: {},
                selectedlists: null,
                oldsearch : '',
                search: '', //快捷搜索--字段
                filter: {},//高级搜索--字段
                op: {},//高级搜索--条件
                loading: false,
                limit: 10, //分页，每页数量
                offset: 0, //从第几行开始
                totalItemsCount: 0,  //共多少条数据
                sort: 'id',  //排序键名
                order: 'desc',  //排序方式
                dataKey: 'id',//唯一字段，（主键）

                controlRout:'/product_order_channel', //控制器
                home: {label: '控制台', icon: 'pi pi-home', to: '/'}, //面包屑公共导航
                crumbs: [ //面包屑
                ],
                tabmenuItems: [ //选项卡
                    {
                        label: '全部', icon: 'pi pi-fw pi-home', class: 'p-highlight',
                        command: (event) => {
                            this.setTabChecked(event);
                            this.clearFilter();
                            this.getListsTable();
                        }
                    },
                    {
                        label: '正常',class: '',
                        command: (event) => {
                            this.setTabChecked(event);
                            this.setFilter('status', "1");
                            this.getListsTable();
                        }
                    },
                    {
                        label: '禁用', class: '',
                        command: (event) => {
                            this.setTabChecked(event);
                            this.setFilter('status', "0");
                            this.getListsTable();
                        }
                    },
                ],
            }
        },
        TableService: null,
        created() {
            this.scrollable = document.body.clientWidth > 960;
            this.TableService = new TableService();
            //获取当前路由名称
            for (let i = 0; i < this.$router.options.routes[1].children.length ; i++){
                if(this.$router.options.routes[1].children[i].path === this.$route.fullPath){
                    this.crumbs = [
                        {label: '渠道管理', },
                        {label: this.$router.options.routes[1].children[i].meta.title},
                    ];
                }
            }
        },
        mounted() {
            this.getListsTable();
            // 监听窗口大小
            window.onresize = () => {
                return (() => {
                    this.screenWidth = document.body.clientWidth
                })()
            };
        },
        methods: {
            updateSort(event)   //排序
            {
                if(event.multiSortMeta.length === 0) {
                    this.sort = this.dataKey;  //排序键名
                    this.order = 'desc';  //排序方式
                }else{
                    this.sort = event.multiSortMeta[0].field;  //排序键名
                    this.order = event.multiSortMeta[0].order===1 ? 'desc' : 'asc';  //排序方式
                }
                this.getListsTable();
            },
            refreshTab()  //刷新表格
            {
                this.getListsTable();
            },
            getListsTable(operation = null)  //获取表格数据
            {
                this.empty = '没有找到匹配的记录';
                let params = {
                    search: this.search,
                    filter: this.filter,
                    op: this.op,
                    limit: this.limit,
                    offset: this.offset,
                    sort: this.sort,
                    order: this.order,
                };
                this.loading = true;
                this.lists = null;
                this.totalItemsCount = 0;
                this.TableService.get(this.controlRout + '/list', params).then(data => {
                    if(data === undefined) {
                        this.empty = 'ERROR: 结果返回异常';
                        this.loading = false;
                        return;
                    }else if(typeof(data) === 'object' && data.code !== 20000){
                        this.empty = 'ERROR: '+data.msg;
                        this.loading = false;
                        return;
                    }
                    this.lists = data.data.rows;
                    this.totalItemsCount = data.data.total;
                    this.loading = false;

                    try {
                        if(operation.search || this.oldsearch) {
                            setTimeout(function () {
                                document.getElementById('search_input').focus();
                            }, 10);
                        }
                    }catch (e) {
                        // console.log('e:'+e.message); //隐藏undefined
                    }
                });
            },
            setFilter(name, value, symbol = "=")  //设置查询条件
            {
                if(value === ""){
                    delete this.filter[name];
                    delete this.op[name];
                    return;
                }
                name = name.replace(/^\s+|\s+$/g,"");
                value = value.replace(/^\s+|\s+$/g,"");
                symbol = symbol.replace(/^\s+|\s+$/g,"");
                this.filter[name] = value;
                this.op[name] = symbol;
                console.log('filter:' + JSON.stringify(this.filter));
            },
            clearFilter()  //清空查询条件
            {
                this.search = ''; //快捷搜索--字段
                this.oldsearch = '';
                this.filter = {};//高级搜索--字段
                this.op = {};//高级搜索--条件
                this.sort = 'id';  //排序键名
                this.order = 'desc';  //排序方式
            },
            setTabChecked(event){  //选项卡选中
                for (let i = 0; i < this.tabmenuItems.length ; i++){
                    this.tabmenuItems[i].class = '';
                }
                event.item.class = 'p-highlight';
            },
            onPage(event)   //下一页
            {
                this.limit = event.rows;
                this.offset = event.first;
                this.getListsTable();
            },
            formatCurrency(value)  //格式化时间
            {
                return value.toLocaleString('en-US', {style: 'currency', currency: 'USD'});
            },
            hideDialog() {
                this.listDialog = false;
                this.submitted = false;
            },
            openNew() {
                this.edit_title = '新建';
                this.list = {};
                this.submitted = false;
                this.listDialog = true;
            },
            savelist()   //提交编辑或新建
            {
                this.editSaveIcon = 'pi pi-spin pi-spinner p-button-icon p-button-icon-left';
                this.editSaveDisabled = true;
                this.submitted = true;

                this.list.status = !!this.list.status;

                this.TableService.post(this.controlRout + (this.list.id ? '/edit' : '/add'), this.list).then(data => {
                    this.editSaveIcon = 'pi pi-check p-button-icon p-button-icon-left';
                    this.editSaveDisabled = false;
                    if (data === undefined) {
                        return;
                    }
                    if (typeof (data) === 'object' && data.code !== 20000) {
                        return;
                    }
                    this.$toast.add({severity: 'success', summary: '提示', detail: data.msg, life: 3000});
                    //清空表单数据
                    this.listDialog = false;
                    this.list = {};
                    //清空搜索条件
                    this.clearFilter();
                    //刷新表格
                    this.getListsTable();
                });
            },
            editlist(list)  //编辑行
            {
                let params = {
                    [this.dataKey]: list.[this.dataKey]
                };
                this.edit_title = '正在编辑：#' + list.[this.dataKey];
                this.loading = true;
                this.TableService.get(this.controlRout + '/edit', params).then(data => {
                    if (data === undefined) {
                        this.$toast.add({severity: 'info', summary: '提示', detail: '数据获取失败', life: 3000});
                        this.loading = false;
                        return;
                    } else if (typeof (data) === 'object' && data.code !== 20000) {
                        this.$toast.add({severity: 'info', summary: '提示', detail: data.msg, life: 3000});
                        this.loading = false;
                        return;
                    }

                    //渲染表单数据
                    this.list = {...data.data};
                    this.loading = false;
                    //显示表单
                    this.listDialog = true;
                });
            },
            deletelist(list) {  //提交删除行
                let params = {
                    [this.dataKey]: list.[this.dataKey]
                };
                this.TableService.post(this.controlRout + '/del', params).then(data => {
                    if (data === undefined) {
                        return;
                    }
                    if (typeof (data) === 'object' && data.code !== 20000) {
                        return;
                    }
                    this.$toast.add({severity: 'success', summary: '提示', detail: data.msg, life: 3000});
                    //清空表单数据
                    this.deletelistDialog = false;
                    this.list = {};
                    //清空搜索条件
                    this.clearFilter();
                    //刷新表格
                    this.getListsTable();
                });
            },
            deleteSelectedlists() //批量删除
            {
                let ids = [];
                let selectedlists = this.lists.filter(val => this.selectedlists.includes(val));
                for (let key in selectedlists) {
                    if(selectedlists[key].[this.dataKey] !== undefined) {
                        ids.push(selectedlists[key].[this.dataKey]);
                    }
                }
                ids = ids.join(",");

                let params = {
                    [this.dataKey]: ids
                };
                this.TableService.post(this.controlRout + '/del', params).then(data => {
                    if (data === undefined) {
                        return;
                    }
                    if (typeof (data) === 'object' && data.code !== 20000) {
                        return;
                    }
                    this.$toast.add({severity: 'success', summary: '提示', detail: data.msg, life: 3000});
                    //清空表单数据
                    this.deletelistsDialog = false;
                    this.selectedlists = null;
                    //清空搜索条件
                    this.clearFilter();
                    //刷新表格
                    this.getListsTable();
                });
            },
            confirmDeletelist(list) {
                this.list = list;
                this.deletelistDialog = true;
            },
            confirmDeleteSelected() {
                this.deletelistsDialog = true;
            },
            confirmSwitch(list)   //状态开关
            {
                console.log('list:'+JSON.stringify(list.status));
                let params = {
                    [this.dataKey] : list.[this.dataKey],
                    key : 'status',
                    update: list.status ? 0 : 1,
                };
                this.TableService.get(this.controlRout + '/switch', params).then(data => {
                    if(data.code === 20000){
                        this.$toast.add({severity: 'success', summary: '提示', detail: '切换成功', life: 3000});
                        return;
                    }
                    this.getListsTable();
                });
            },
        },
        watch: {
            screenWidth (val)
            {
                this.scrollable = val > 960;   //适配移动端预览，关闭滚动列表
            },
            search(val)  //搜索框
            {
                if(val.replace(/^\s+|\s+$/g,"") === this.oldsearch.replace(/^\s+|\s+$/g,""))
                {
                    return; //解决输入文字时无效提交
                }
                this.oldsearch = val;
                this.getListsTable({search:true});
            }
        },
    }
</script>

<style scoped lang="scss">
    .table-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .confirmation-content {
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .list-badge {
        border-radius: 2px;
        padding: .25em .5rem;
        text-transform: uppercase;
        font-weight: 700;
        font-size: 12px;
        letter-spacing: .3px;

        &.status-有现货 {
            background: #C8E6C9;
            color: #256029;
        }

        &.status-缺货 {
            background: #FFCDD2;
            color: #C63737;
        }

        &.status-lowstock {
            background: #FEEDAF;
            color: #8A5340;
        }
    }

    @media screen and (max-width: 960px) {
        /deep/ .p-datatable {
            &.p-datatable-customers {
                .p-datatable-thead > tr > th,
                .p-datatable-tfoot > tr > td {
                    display: none !important;
                }

                .p-datatable-tbody > tr {
                    border-bottom: 1px solid var(--surface-d);

                    > td {
                        text-align: left;
                        display: block;
                        border: 0 none !important;
                        width: 100% !important;
                        float: left;
                        clear: left;
                        border: 0 none;

                        .p-column-title {
                            padding: .4rem;
                            min-width: 30%;
                            display: inline-block;
                            margin: -.4rem 1rem -.4rem -.4rem;
                            font-weight: bold;
                        }

                        .p-progressbar {
                            margin-top: .5rem;
                        }
                    }
                }
            }
        }

        /deep/ .p-toolbar {
            flex-wrap: wrap;

            .p-button {
                margin-bottom: .25rem;
            }
        }
    }

    .tabview-custom {
        i, span {
            vertical-align: middle;
        }

        span {
            margin: 0 .5rem;
        }
    }
    .p-multiselect {
        min-width: 15rem;
    }

    .multiselect-custom {

        .p-multiselect-label:not(.p-placeholder) {
            padding-top: .25rem;
            padding-bottom: .25rem;
        }

        .country-item {
            display: flex;
            align-items: center;

            span.flag {
                width: 18px;
                height: 12px;
                margin-right: .5rem;
                margin-left: .5rem;
            }
        }

        .country-item-value {
            border-radius: 3px;
            display: inline-flex;
            margin-right: .5rem;
            background-color: var(--primary-color);
            color: var(--primary-color-text);
        }
    }

    .special-day {
        text-decoration: line-through;
    }

    /**
    小头像
     */
    .img-center {
        margin: 0 auto;
        display: inline;
        float: none;
    }

    .img-sm, .box-comments .box-comment img, .user-block.user-block-sm img {
        width: 6.5rem !important;
        height: 6.5rem !important;
    }

    /**
    切换开关
     */
    .p-button.p-highlight {
        background: #2196F3;
        border-color: #2196F3;
        color: #ffffff;
    }
    .p-button:not(.p-disabled):not(.p-highlight):hover {
        background: #e9ecef;
        border-color: #ced4da;
        color: #495057;
    }

    /**
    标签卡
     */
    .status-success {
        background: #c8e6c9;
        color: #256029;
    }
    .p-tabview-panels{
        padding: 0;
    }
</style>
